<template>
    <div class="upload-js">
        <br />
        <label for="fileInput" style="margin-left: 120px;margin-top: 20px">选择相册照片</label>
        <input type="file" id="fileInput" accept=".jpg, .jpeg, .png" style="display: none;" />
        &nbsp;
        <!-- <van-progress :percentage="Progress" stroke-width="8" /> -->
    </div>
</template>

<script lang="ts" setup>
import { onMounted, onUnmounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router'
const route = useRoute()
const router = useRouter()

let ws: WebSocket = new WebSocket('ws://localhost:3333');
const chunkSize = 1024 * 1024; // 1MB

const Progress = ref(0);

onMounted(() => {
    const fileInput: HTMLElement | null = document.getElementById('fileInput') as HTMLElement;
    ws.onopen = () => {
        console.log('连接成功');
    };

    ws.onerror = (err) => {
        console.log('连接失败', err);
    };

    ws.onmessage = (event) => {
        const message = JSON.parse(event.data);
        if (message.type === 'progress') {
            const { progress } = message;
            Progress.value = progress;
            router.back()
        }
    }

    // 在这里安全地使用 fileInput，因为它已确认不是 null
    fileInput.addEventListener('change', (event: Event) => {
        const file = (event!.target as HTMLInputElement).files![0];

        const fileName = file.name; // 文件名

        const reader = new FileReader();  // 文件对象读取
        reader.onload = (event: ProgressEvent<FileReader>) => {
            if (event.target !== null) {
                const arrayBuffer = event.target.result as ArrayBuffer; // 文件数据
                const totalChunks = Math.ceil(arrayBuffer.byteLength /
                    chunkSize); // 总块数

                ws.send(JSON.stringify({ fileName, totalChunks }))
                for (let i = 0; i < totalChunks; i++) {
                    const start = i * chunkSize;
                    const end = Math.min(start + chunkSize, arrayBuffer.byteLength);
                    const chunk = arrayBuffer.slice(start, end);
                    ws.send(chunk);
                    // 处理分块传输
                }
            }
        }
        reader.readAsArrayBuffer(file);
    })
})
onUnmounted(() => {
    console.log('关闭WebSocket连接');

    // 组件卸载时关闭WebSocket连接
    ws.close();
})




</script>
<style lang="scss" scoped></style>